package com.yls.except.filter;

import java.io.IOException;
import java.util.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yls.except.task.RedisCash;
import com.yls.except.util.*;
import com.yls.except.util.exception.ExceptionHandle;

/**
 * 登录过滤器
 * 
 * @author xusheng
 * @time 2015-7-9 上午9:22:02
 * @version 1.0
 * @Description: {}
 * 
 */
public class LoginFilter extends ExceptionHandle implements Filter {
	@SuppressWarnings("unused")
	private FilterConfig filterConfig;

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String json = req.getParameter("json");
		Map<String, Object> map = GeneralResult.jsonStrToMap(json);
		String token = map.get("token") + "";
		List<Object> list = new ArrayList<Object>();
		String item = ImgProperties.getConstan("itemname");
		if (StringIsempty.isallempty(token)) {
			GeneralResult.general(resp, list, 10001, 0); // 参数有误
		} else {
			token = HexString.decode(token);
			token = HexString.removestr(token, 6, item, "");
			Map<String, String> utokenmap = RedisCash.getMap(token);
			boolean flag = false;
			if (StringIsempty.isNullMap(utokenmap)) {
				GeneralResult.general(resp, list, 10001, 0); // 未登录
			} else {
				String uid = utokenmap.get("uid");
				String type = utokenmap.get("type");
				String openid = utokenmap.get("openid");
				long datetime = Long.parseLong(utokenmap.get("time"));
				long timestamp = new Date().getTime();
				long mistaketime = timestamp - datetime;
				double time = mistaketime / 1000 / 60 / 60 / 24;
				time = Math.abs(time);
				if(StringIsempty.isallempty(uid) || StringIsempty.isallempty(type))
					GeneralResult.general(resp, list, 10002, 0);
				else if(time <= ConstantUtil.LONGTIME){
					req.setAttribute("uid", uid);
					req.setAttribute("type", type);
					req.setAttribute("openid", openid);
					utokenmap.put("time", timestamp + "");
					RedisCash.redisMap("life" + token, utokenmap);
					chain.doFilter(req, resp);
				} else {
					GeneralResult.general(resp, list, 10002, 0); // 登录超时
				}
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
}
